<template>
    <div class="mychar" :id="id" :style="{ width: width, height: height }"></div>
</template>

<script>
export default {
    props: {
        id: {
            type: String,
            default: "myChart",
        },

        width: {
            type: String,
            default: "300px",
        },

        height: {
            type: String,
            default: "300px",
        },

        item: {
            type: Array,
            default: () => [],
        },

        date: {
            type: Array,
            default: () => [],
        },

        // type: {
        //     type: String,
        //     default: "line",
        // },
    },

    data() {
        return {
            myChart: "",
            type: "line",
        };
    },

    methods: {
        drawLine() {
            // 基于准备好的dom，初始化echarts实例
            var chartEle = document.getElementById(this.id);
            let myChart = this.$echarts.init(chartEle);
            // 绘制图表
            setTimeout(() => {
                this.option = {
                    tooltip: {
                        trigger: "axis",
                    },

                    toolbox: {
                        feature: {
                            magicType: { show: true, type: ["line", "bar"] },

                            saveAsImage: { show: true },
                        },
                    },

                    legend: {
                        data: this.item.map((m) => m.stock_name),
                        type: "scroll",
                        width: 800,
                    },
                    grid: {
                        left: "3%",
                        right: "4%",
                        bottom: "3%",
                        containLabel: true,
                    },

                    xAxis: {
                        type: "category",
                        data: this.date,
                    },

                    yAxis: {
                        type: "value",
                    },

                    series: this.item.map((m) => ({
                        name: m.stock_name,
                        type: this.type,
                        data: m.items.map((m) => {
                            return [m.date, m.value.toFixed(2)];
                        }),
                    })),
                };
                myChart.setOption(this.option);
            }, 500);
            this.myChart = myChart;
        },

        resize() {
            this.myChart.resize();
        },

        dispose() {
            this.myChart.dispose();
        },

        change(type) {
            this.type = type;
            this.drawLine();
        },
    },

    mounted() {
        this.drawLine();
    },
};
</script>

<style lang="scss" scoped></style>
